#! /bin/bash

# ----------------------------------------------------------------------------
#
# Start plotting.
#
# yqm_leaf@163.com
#
# 05/02/21
#
# ----------------------------------------------------------------------------

ARCH_FILE="/usr/share/chia-blockchain/app.asar.unpacked/daemon/chia "
UBUNTU_FILE="/usr/lib/chia-blockchain/resources/app.asar.unpacked/daemon/chia"
BIN_PATH="/usr/local/bin/"

NUM_THREADS=4
PLOT_BUFFER=4608

usage () {
    echo "$0 -t [tmp dir] -d [destination dir]"
}

gen_log_filename () {
    local num=50 # let's make it big.
    local prefix="plotting"
    local suffix=".log"
    for i in $(seq 1 ${num}) ; do
        local file_name="${prefix}${i}${suffix}"
        [ -a ${file_name} ] && continue
        break
    done
    # This will overwite 50th log file if files exists.
    echo ${file_name}
}

while getopts ":t:d:" opt ; do
  case $opt in
    t)
      TEMP_DIR=${OPTARG}
      ;;
    d)
      DST_DIR=${OPTARG}
      ;;
    \?)
      usage
      exit 1;;
    :)
      echo "Option -$OPTARG requires an argument. -h to see more."
      exit 1;;
  esac
done

# Quit on missing args.
[ -z $TEMP_DIR ] || [ -z $DST_DIR ] && \
    { echo "tmp dir or destination dir missing" ; usage ; exit 1 ; }

LOG_FILE=$(gen_log_filename)
PLOT_CMD="chia plots create -n 1 -r ${NUM_THREADS} -b ${PLOT_BUFFER} -t ${TEMP_DIR} -d ${DST_DIR} | tee ${LOG_FILE}"

# Need sudo to create symbolic links in "/usr/local/bin".
type sudo > /dev/null 2>&1 || \
    { echo "sudo needed, please install it first." ; 
      exit 1 ;
    }

type chia > /dev/null 2>&1
if [ $? -ne 0 ] ; then
    echo "'chia' command not in PATH, creating soft links"
    # Ubuntu based.
    [ -f "${UBUNTU_FILE}" ] && \
        sudo ln -sf ${UBUNTU_FILE} ${BIN_PATH}
    # Arch linux based.
    [ -f "${ARCH_FILE}" ] && \
        sudo ln -sf ${ARCH_FILE} ${BIN_PATH}
fi

type chia > /dev/null 2>&1 || \
    { echo "Failed to find chia on the system, is it installed?" ; exit 1 ; }

[ -z $TMUX ] && [ -z $STY ] && \
    echo "WARNING: Run this script in a tmux/screen session is recommended."
echo ${PLOT_CMD}
eval $PLOT_CMD
